%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%% Homogenous AR(1) prewhitening procedure
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function eh = prwp(x)

t = size(x,1);
mx = x;

mxx = mx(1:t-1,:);
mx1 = mx(1:t-1,:);
mx1 = mx1 - repmat(mean(mx1),t-1,1);
mx1 = mx1 - repmat(mean(mx1),t-1,1);

mxy = mx(2:t,:);
mx2 = mx(2:t,:);
mx2 = mx2 - repmat(mean(mx2),t-1,1);
mx2 = mx2 - repmat(mean(mx2),t-1,1);

rh = sum(sum(mx1.*mx2))./sum(sum(mx1.*mx1));
rh = mf(rh,t);
eh = mxy - rh*mxx;


function rn = mb(r,t)

a1 = -(1+r)./(t-1);
a2 = 1 - ((1-r.^t)./(1-r))./t;
a3 = 1 - (2.*r./((t-1).*(t-r))).*a2;
rn = (a1.*a2)./a3;


function rh = mf(rh,t)

tt = 998;
rq = seqa(-0.999,0.002,tt);
rn = mb(rq,t-1);
rn = rq + rn;
rh = minindc(abs(rn - rh)); 
rh = rq(rh);

